import {
  Complex
} from '../api/complex'

class ClassicModel extends Complex {
  getClassicLast () {
    return new Promise(resolve => {
      this.$axios({
        url: 'classic/latest'
      }).then(res => {
        this._setLatestIndex(res.index)
        let key = this._getKey(res.index)
        localStorage.setItem(key, JSON.stringify(res))
        resolve(res)
      })
    })
  }

  getClassic (index, nextOrPrev) {
    let key = nextOrPrev === 'next' ? this._getKey(index + 1) : this._getKey(index - 1)
    let classic = JSON.parse(localStorage.getItem(key))
    if (!classic) {
      return new Promise(resolve => {
        this.$axios({
          url: `classic/${index}/${nextOrPrev}`
        }).then(res => {
          let key = this._getKey(res.index)
          localStorage.setItem(key, JSON.stringify(res))
          resolve(res)
        })
      })
    } else {
      return new Promise(resolve => {
        resolve(classic)
      })
    }
  }

  isFirst (index) {
    return index === 1
  }

  isLatest (index) {
    let latestIndex = this._getLatestIndex()
    return index === latestIndex
  }

  _setLatestIndex (index) {
    localStorage.setItem('latest', JSON.stringify(index))
  }

  _getLatestIndex () {
    let index = JSON.parse(localStorage.getItem('latest'))
    return index
  }

  _getKey (index) {
    let key = `classic-${index}`
    return key
  }
}

export {
  ClassicModel
}
